package com.itheima.health.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.mapper.OrderMapper;
import com.itheima.health.pojo.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitMQListener {


    @Value("${sunspring.dlx.queue}")
    private String dlxQueue;

    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = "dlx_queue")
    public void dlxListener(Integer orderId , Message message, Channel channel) throws IOException {
        System.out.println(orderId);
        System.out.println(new String(message.getBody()));
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //对消息进行业务处理....
        //根据id判断isPay是否为0,一条sql语句
        try{
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getId,orderId)
                    .eq(Order::getIsPay,0);
            int deleteIndex = orderMapper.delete(wrapper);

            System.out.println(deleteIndex);

            //释放
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            //不释放,重新放入队列
            e.printStackTrace();
            channel.basicNack(deliveryTag,false,true);
        }
    }
}
